package com.jian.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Jiange
 * @create 2021-04-11-22:35
 */
public class JDBCUtils {
    private static Connection connection = null;
    private static Properties properties ;
    private static InputStream inputStream;
    private static ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();

    static {
        try {
            properties = new Properties();
            inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("JDBC.properties");
            System.out.println(inputStream);
            properties.load(inputStream);
            DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
            connection = dataSource.getConnection();
            connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            connection.setAutoCommit(false);
            connectionThreadLocal.set(connection);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        } finally {
        }
    }

    public static Connection getConnection() {
        connection = connectionThreadLocal.get();
        System.out.println("JDBCUtils"+"---"+connection);
        if(connection == null){
            try {
                DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
                connection = dataSource.getConnection();
                connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
                connection.setAutoCommit(false);
                connectionThreadLocal.set(connection);
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
        return connection;
    }

    public static void CloseConnectionSubmit() throws Exception {
        System.out.println("关闭数据库的连接");
        connection = connectionThreadLocal.get();
        System.out.println("1");
        connection.commit();
        System.out.println();
        connection.setAutoCommit(true);
        System.out.println("3");
        connection.close();
        System.out.println("间隔随帅");
        connectionThreadLocal.remove();
        System.out.println("成功");
    }

    public static void CloseRollback() throws Exception {
        connection = connectionThreadLocal.get();
        connection.rollback();
        connection.setAutoCommit(true);
        connection.close();
        connectionThreadLocal.remove();
    }
}
